import {canMes} from "./getPhone"  //获取到随机生成的验证码
import { mongo } from '#nuxt-mongodb';

interface UserSubmit {
    name:string,
    account:string,
    password:string
}

//创建一个user对象
let user:UserSubmit = {
    name: '用户名' as string,
    account: '' as string,
    password:'123456' as string
}

interface phoneInter {
    phone:string,
    can1:string,//验证码
}

//用户注册的API
//只有注册账号才能使用(模拟手机短信发送(因为真正的短信发送要钱))
export default defineEventHandler(async(event:any)=>{
    // console.log("canMes:",canMes,"canMes typeof:",typeof canMes) //提示发送信息
    try{
        const {phone,can1}:phoneInter = await readBody(event)
        const result = await mongo.db().collection('user').findOne({account:phone})
        if(result){
            return {
                status: 200,
                data: result,
                message: "你已经注册过账号"
            }
        }
        user.account = await phone
        //如果以下console.log出现(can typeof: undefined canMes typeof: number canMesStr typeof: string)那么就尝试把can转成string类型
        // const canValue:string = can.toString() 
        // console.log("can1:",can1,"can1 typeof:",typeof can1)
        const canValue = Number(can1) || 0 //转换失败为0
        // const canMesStr = canMes.toString()
        console.log("can1Value:",canValue,"can1Value typeof:",typeof canValue)
        if(canValue === canMes){ //输入的验证码can1和之前请求的canMes是同一个
            //连接mongodb
            const users = mongo.db().collection('user')
            console.log('phone:',phone,"phone type:",typeof phone)//确认phone
            console.log('user:',user) //确认user
            const result = await users.insertOne({
                name:user.name ?? '',
                account:user.account ?? '',
                password:user.password ?? ''})
                console.log(result)
            return {
                status: 200,
                message: "register success"
            }
        }else if(canMes == 0){
            return {
                status:500,
                message: "验证码为空"
            }
        }else{
            return {
                status: 503,
                message: "验证码错误"
            }
        }
    }catch(err:any){
        return{
            status: 500,
            message: "register error",
            data:err
        }
    }
})